const app = getApp()
Page({
    data: {
        telAddressList:[],
        keyword: '', // 用户输入的关键字
    matchedIndexes: [] // 匹配到的索引数组
    },
    onLoad(){
        this.setData({
            canIUseGetUserProfile: true,
            nbTitle: '号码归属地查询',
          nbLoading: true,
          nbFrontColor: '#ffffff',
          nbBackgroundColor: '#000000'
          })
        wx.request({
            url: 'https://guitarfish.top/applet/telephoneCodeInformationApi/getPhoneCode',
            method: 'GET',
            header: {
              'Content-Type': 'application/json'
            },
            success: res=> {
              console.log(res.data.data); // 打印请求成功后返回的数据
              this.setData({
                telAddressList:res.data.data,
                nbLoading:false
              })
            },
            fail: error=> {
              console.log(error); // 打印请求失败的错误信息
            }
          });
    },
     // 监听搜索框的输入事件
  handleSearchInput(e) {
    const keyword = e.detail.value.trim();
    this.setData({ keyword });

    // 根据关键字进行匹配和定位
    this.searchAndLocate(keyword);
  },

  searchAndLocate(keyword) {
    const { telAddressList } = this.data;
    const matchedIndexes = [];

    // 遍历已经渲染的页面数据，查找匹配的内容并记录索引
    for (let i = 0; i < telAddressList.length; i++) {
      if (telAddressList[i].zhCn.includes(keyword)) {
        matchedIndexes.push(i);
      }
    }
    console.log(matchedIndexes)

    this.setData({ matchedIndexes });

    // 根据匹配到的索引执行滚动操作
    if (matchedIndexes.length > 0) {
      const targetIndex = matchedIndexes[0]; // 这里示例取第一个匹配到的索引
      const query = wx.createSelectorQuery();
      query.select(`#item-${targetIndex}`).boundingClientRect();
      query.selectViewport().scrollOffset();
      query.exec((res) => {
        const targetRect = res[0];
        const scrollTop = targetRect.top-85; // 计算滚动的位置
        wx.pageScrollTo({
          scrollTop: scrollTop
        });
      });
    }
},
// onPageScroll(e) {
//     const scrollTop = e.scrollTop;
//     const searchContainer = this.selectComponent('.search-container');

//     if (searchContainer) {
//       if (scrollTop > 0) {
//         searchContainer.setStyle({
//           position: 'static'
//         });
//       } else {
//         searchContainer.setStyle({
//           position: 'fixed',
//           top: '0'
//         });
//       }
//     }
//   }
onPageScroll(e) {
    const scrollTop = e.scrollTop;
    const searchContainer = this.selectComponent('.search-container');

    if (searchContainer) {
      const windowHeight = wx.getSystemInfoSync().windowHeight;
      const searchContainerHeight = searchContainer.offsetHeight;

      if (scrollTop > windowHeight - searchContainerHeight) {
        searchContainer.style.top = windowHeight - searchContainerHeight + 'px';
      } else {
        searchContainer.style.top = 0;
      }
    }
  }
})